import {
	ref,
	computed,
	onMounted,
	watch
} from 'vue';
import ToolAction from "@/tool/http/ToolActionApi.js";

let apiTag = ToolAction.init('common_tag');

export default function useTags(defaultCheckTagIds = []) {
	const tags = ref([]);
	defaultCheckTagIds = defaultCheckTagIds || []

	const initList = async () => {
		let res = await apiTag.list();
		res.filter(item => defaultCheckTagIds.includes(item.id)).forEach(item => item.checked = true);
		tags.value = res;
		return tags.value;
	}

	onMounted(() => {
		initList()
	})

	const remove = (id) => {
		apiTag.remove(id).then(res => {
			tags.value = tags.value.filter(tag => tag.id !== id);
		});
	}

	const check = (tag) => {
		tag.checked = !tag.checked;
	}

	const checkList = (ids) => {
		tags.value.forEach(item => item.checked = false);
		tags.value.filter(item => ids.includes(item.id)).forEach(item => item.checked = true);
	}

	const checkTags = computed({
		get() {
			return tags.value.filter(item => item.checked).map(item => item.id);
		},
		set(val) {
			checkList(val);
		}
	})

	const add = (name) => {
		if (!name || tags.value.find(item => item.name === name)) {
			return;
		}
		apiTag.sync({
			name
		}).then(res => {
			tags.value = [...tags.value, {
				name
			}];
		})
	}

	let watchListen = () => {};

	const addWatchCheck = (listen) => {
		watchListen = listen;
	}

	const transformName = (ids = []) => {
		return tags.value.filter(item => ids.includes(item.id)).map(item => item.name);
	}

	watch(checkTags, (val) => {
		watchListen(val);
	})

	return {
		tags,
		remove,
		check,
		checkTags,
		add,
		addWatchCheck,
		transformName,
		initList
	}
}
